// 路由修复工具 - 专门处理刷新404问题
import router from '../router'
import { useUserStore } from '../stores/user'
import { usePermissions } from '../stores/permission'
import { isTokenExpired } from './tokenUtils'

/**
 * 路由修复管理器
 */
class RouteFixManager {
  constructor() {
    this.isFixing = false
    this.fixPromise = null
    this.retryCount = 0
    this.maxRetries = 3
  }

  /**
   * 检查并修复路由问题
   * @param {string} targetPath 目标路径
   * @returns {Promise<boolean>} 是否修复成功
   */
  async checkAndFix(targetPath) {
    // 如果正在修复中，等待修复完成
    if (this.isFixing && this.fixPromise) {
      console.log('路由修复正在进行中，等待完成...')
      return await this.fixPromise
    }

    // 开始修复流程
    this.isFixing = true
    this.fixPromise = this._performFix(targetPath)

    try {
      const result = await this.fixPromise
      return result
    } finally {
      this.isFixing = false
      this.fixPromise = null
    }
  }

  /**
   * 执行路由修复
   * @param {string} targetPath 目标路径
   * @returns {Promise<boolean>} 是否修复成功
   */
  async _performFix(targetPath) {
    console.log(`开始修复路由问题: ${targetPath}`)

    try {
      // 1. 检查基本状态
      const basicCheck = await this._checkBasicState()
      if (!basicCheck.isValid) {
        console.log('基本状态检查失败:', basicCheck.reason)
        return false
      }

      // 2. 确保权限数据已加载
      const permissionCheck = await this._ensurePermissionsLoaded()
      if (!permissionCheck) {
        console.log('权限数据加载失败')
        return false
      }

      // 3. 确保动态路由已加载
      const routeCheck = await this._ensureDynamicRoutesLoaded()
      if (!routeCheck) {
        console.log('动态路由加载失败')
        return false
      }

      // 4. 验证目标路由
      const routeExists = await this._verifyTargetRoute(targetPath)
      if (!routeExists) {
        console.log(`目标路由不存在或无权限访问: ${targetPath}`)
        return false
      }

      console.log(`路由修复成功: ${targetPath}`)
      return true

    } catch (error) {
      console.error('路由修复过程中出错:', error)
      
      // 如果是认证错误，清除状态
      if (error.response && (error.response.status === 401 || error.response.status === 403)) {
        const userStore = useUserStore()
        userStore.logout()
        router.push('/login')
      }
      
      return false
    }
  }

  /**
   * 检查基本状态
   * @returns {Promise<{isValid: boolean, reason?: string}>}
   */
  async _checkBasicState() {
    const userStore = useUserStore()
    const token = localStorage.getItem('token')

    // 检查token
    if (!token || isTokenExpired(token)) {
      return { isValid: false, reason: 'Token无效或已过期' }
    }

    // 确保用户状态已初始化
    if (!userStore.isLoggedIn || !userStore.isInitialized) {
      console.log('初始化用户状态...')
      const success = userStore.syncFromStorage()
      userStore.setInitialized(true)
      
      if (!success) {
        return { isValid: false, reason: '用户状态同步失败' }
      }
    }

    return { isValid: true }
  }

  /**
   * 确保权限数据已加载
   * @returns {Promise<boolean>}
   */
  async _ensurePermissionsLoaded() {
    const { userMenus } = usePermissions()

    // 如果权限数据已存在，直接返回
    if (userMenus.value && userMenus.value.length > 0) {
      console.log('权限数据已存在')
      return true
    }

    console.log('加载权限数据...')
    try {
      const { getUserInfo } = await import('../api/auth')
      const { setUserPermissions } = await import('../stores/permission')

      const response = await getUserInfo()
      if (response.data && response.data.menus) {
        setUserPermissions(
          response.data.buttons || [],
          response.data.menus || [],
          response.data
        )
        console.log('权限数据加载成功')
        return true
      }

      console.log('权限数据为空')
      return false
    } catch (error) {
      console.error('加载权限数据失败:', error)
      throw error
    }
  }

  /**
   * 确保动态路由已加载
   * @returns {Promise<boolean>}
   */
  async _ensureDynamicRoutesLoaded() {
    const { userMenus } = usePermissions()
    
    if (!userMenus.value || userMenus.value.length === 0) {
      console.log('没有菜单数据，无法加载动态路由')
      return false
    }

    console.log('加载动态路由...')
    try {
      const { addDynamicRoutes, clearDynamicRoutes } = await import('../router')
      
      // 清除现有动态路由
      clearDynamicRoutes()
      
      // 重新加载动态路由
      await addDynamicRoutes(userMenus.value)
      
      console.log('动态路由加载成功')
      return true
    } catch (error) {
      console.error('加载动态路由失败:', error)
      return false
    }
  }

  /**
   * 验证目标路由
   * @param {string} targetPath 目标路径
   * @returns {Promise<boolean>}
   */
  async _verifyTargetRoute(targetPath) {
    // 检查路由是否存在
    const allRoutes = router.getRoutes()
    const targetRoute = allRoutes.find(r => r.path === targetPath)
    
    if (!targetRoute) {
      console.log(`路由不存在: ${targetPath}`)
      return false
    }

    // 检查权限
    if (targetRoute.meta?.requiresMenu) {
      const { userMenus } = usePermissions()
      const { hasRoutePermission } = await import('../router/dynamicRoutes')
      
      const menuPath = targetRoute.meta.menuPath || targetPath
      const hasPermission = hasRoutePermission(menuPath, userMenus.value)
      
      if (!hasPermission) {
        console.log(`无权限访问路由: ${targetPath}`)
        return false
      }
    }

    console.log(`路由验证通过: ${targetPath}`)
    return true
  }

  /**
   * 重置修复状态
   */
  reset() {
    this.isFixing = false
    this.fixPromise = null
    this.retryCount = 0
  }
}

// 创建全局实例
const routeFixManager = new RouteFixManager()

/**
 * 路由守卫增强器 - 在现有路由守卫基础上添加修复功能
 */
export function enhanceRouterWithFix() {
  // 在路由导航失败时尝试修复
  router.onError(async (error, to) => {
    console.error('路由导航错误:', error)
    
    if (to && to.path) {
      console.log('尝试修复路由问题...')
      const fixed = await routeFixManager.checkAndFix(to.path)
      
      if (fixed) {
        console.log('路由修复成功，重新导航')
        router.push(to.path).catch(err => {
          console.error('修复后导航仍然失败:', err)
        })
      }
    }
  })

  // 监听404页面，自动尝试修复
  router.afterEach(async (to, from) => {
    if (to.name === 'NotFound' && to.path !== '/404') {
      console.log('检测到404页面，尝试自动修复...')
      
      const fixed = await routeFixManager.checkAndFix(to.path)
      if (fixed) {
        console.log('自动修复成功，重新导航')
        router.replace(to.path).catch(err => {
          console.error('自动修复后导航失败:', err)
        })
      }
    }
  })
}

/**
 * 手动修复路由问题
 * @param {string} path 路径
 * @returns {Promise<boolean>} 是否修复成功
 */
export async function fixRoute(path = null) {
  const targetPath = path || window.location.pathname
  return await routeFixManager.checkAndFix(targetPath)
}

/**
 * 页面刷新时的路由修复
 * 应该在应用启动时调用
 */
export async function fixRouteOnRefresh() {
  const currentPath = window.location.pathname
  
  // 如果是基础路由，不需要修复
  if (['/login', '/403', '/404', '/'].includes(currentPath)) {
    return true
  }

  console.log('页面刷新，检查路由状态...')
  return await routeFixManager.checkAndFix(currentPath)
}

// 导出管理器实例（用于调试）
export { routeFixManager }

// 添加到window对象（开发环境调试用）
if (import.meta.env.DEV) {
  window.fixRoute = fixRoute
  window.routeFixManager = routeFixManager
} 